package com.czxy.changgou3.controller;

import com.czxy.changgou3.config.JwtProperties;
import com.czxy.changgou3.pojo.Address;
import com.czxy.changgou3.pojo.User;
import com.czxy.changgou3.service.AddressService;
import com.czxy.utils.JwtUtils;
import com.czxy.vo.BaseResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author zhangmengxiang1@itcast.cn
 * @version 1.0
 * @date 2020/5/4
 */

@RestController
@RequestMapping("/address")
public class AddressController {

    @Resource
    private AddressService addressService;

    @Resource
    private JwtProperties jwtProperties;

    @Resource
    private HttpServletRequest request;

    @GetMapping
    public BaseResult findAll(){
        //获得登录用户
        String token = request.getHeader("Authorization");
        User loginUser = null;
        try {
            loginUser = JwtUtils.getObjectFromToken(token, jwtProperties.getPublicKey(), User.class);
        } catch (Exception e) {
            return BaseResult.error("token无效");
        }
        //通过用户查询所有收货地址
        List<Address> list = addressService.findAllByUserId(loginUser.getId());
        return BaseResult.ok("查询成功",list);
    }


    @PostMapping
    public BaseResult addAddress(@RequestBody Address address){
        //1 获得用户信息
        // 1.1 获得token
        String token = request.getHeader("Authorization");
        // 1.2 解析token
        User loginUser = null;
        try {
            loginUser = JwtUtils.getObjectFromToken(token, jwtProperties.getPublicKey(),User.class);
        } catch (Exception e) {
            return BaseResult.error("token失效或未登录");
        }

        this.addressService.addAddress(loginUser,address);
        return BaseResult.ok("添加成功");
    }


}
